/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.item

import groovy.util.slurpersupport.GPathResult
import java.io.File
import java.util.Map
import org.ibiblio.terasaur.search.DateHelper
import org.ibiblio.terasaur.user.User

class ItemXmlImporter {
    void importFromFile(String filename) {
        def importFile = new File(filename)
        if (!importFile.exists()) {
            throw new Exception('Unable to find item xml import file: ' + filename)
        }
        def root = new XmlSlurper().parse(importFile)
        _import(root)
    }

    void importFromText(String xmlText) {
        def root = new XmlSlurper().parseText(xmlText)
        _import(root)
    }

    void _import(GPathResult root) {
        root.children().each {element->
            _importItem(element)
        }
    }

    void _importItem(GPathResult element) {
        def itemData = _parseItemElement(element)

        def collection = Collection.get(itemData.collection)
        if (!collection) {
            throw new Exception('Could not find collection for id: ' + itemData.collection)
        }
        itemData.collection = collection

        def user = User.findByUsername(itemData.owner)
        if (!user) {
            throw new Exception('Could not find user for username: ' + itemData.owner)
        }
        itemData.owner = user

        def item = new Item(itemData)
        item.save(insert:true, flush:true, failOnError: true)
    }

    private Map _parseItemElement(GPathResult element) {
        def data = [:]
        data.title = element.title.text()
        data.description = element.description.text()
        data.type = Integer.parseInt(element.type.text())
        data.language = element.language.text()
        data.license = Integer.parseInt(element.license.text())
        data.deleted = (element.deleted.text() == 'true') ? true : false
        data.published = DateHelper.stringToDateTime(element.published.text())
        data.collection = Long.parseLong(element.collection.text())
        data.owner = element.owner.text()
        return data
    }
}
